package com.sky.service.Impl;
import java.util.concurrent.TimeUnit;
import com.alibaba.fastjson2.JSON;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.OpenIdResult;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    public JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public UserLoginVO login(UserLoginDTO logindto) {

        Map<String, String> getOpenid = new HashMap<>();
        getOpenid.put("appid", weChatProperties.getAppid());
        getOpenid.put("secret", weChatProperties.getSecret());
        getOpenid.put("js_code", logindto.getCode());
        getOpenid.put("grant_type", "authorization_code");

        log.info("=========getPoenid{}",getOpenid.toString());

        String result = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", getOpenid);
        OpenIdResult openIdResult = JSON.parseObject(result, OpenIdResult.class);
        String s = openIdResult.getOpenid();
        log.info("===openid :{}",s);

        User u = new User();
        u.setOpenid(s);
        log.info("===s :{}",s);
        User user = userMapper.select(u);
        if(user == null){
            userMapper.Insert(u);
        }
        User UserVO = userMapper.select(u);

        // jwt内封装的内容
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, UserVO.getId());
        claims.put(JwtClaimsConstant.USERNAME, UserVO.getName());
        claims.put(JwtClaimsConstant.PHONE, UserVO.getPhone());

        // 生成token令牌
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        //  把token保存到redis，并且给这个值设置一个过期时间 1小时
        redisTemplate.opsForValue().set("User_token:" + token, UserVO.getId(),1, TimeUnit.HOURS);

        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(UserVO,userLoginVO);

        userLoginVO.setToken(token);

        return userLoginVO;

    }
}
